package Thread.interrupt_thread;

/**
 * 通过共享变量中断线程
 */
public class shared_variable {
    private static class MyThread extends Thread {
        //多个线程都会用到的变量加上volatile关键字
        //表示当前变量是否需要停止
        volatile boolean isQuit=false;

        @Override
        public void run() {
            while (!isQuit){
                System.out.println(Thread.currentThread().getName()+"我一直都在~~");
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            }
            System.out.println(Thread.currentThread().getName()+"我要没了~~");
        }
    }

    public static void main(String[] args) throws InterruptedException {
        MyThread m1=new MyThread();
        Thread thread=new Thread(m1,"线程一~~");
        System.out.println("我还在哦~~");
        thread.start();
        //让主线程暂停3秒，中断子线程
        Thread.sleep(3000);
        System.out.println("我要走了哦~~");
        m1.isQuit=true;
    }

}
